package com.wu.foodsafetyplayer.http;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import static android.content.Context.CONNECTIVITY_SERVICE;

public class NetWorkUtils {
    private static final String TAG = NetWorkUtils.class.getSimpleName();

    public static NetWorkReceiver registerNetWorkReceiver(Context context, IReceiveMessage IReceiveMessage) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        NetWorkReceiver mNetWorkReceiver = new NetWorkReceiver(IReceiveMessage);
        context.registerReceiver(mNetWorkReceiver, intentFilter);
        return mNetWorkReceiver;
    }

    static class NetWorkReceiver extends BroadcastReceiver {

        public IReceiveMessage mIReceiveMessage;

        public NetWorkReceiver(IReceiveMessage IReceiveMessage) {
            // TODO Auto-generated constructor stub
            mIReceiveMessage = IReceiveMessage;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.e(TAG, "onReceive  getAction: " + intent.getAction());
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                    if (mIReceiveMessage != null) {
                        Log.e(TAG, "onReceive: wifi");
                        mIReceiveMessage.onNetConnected();
                    }
                } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                    if (mIReceiveMessage != null) {
                        Log.e(TAG, "onReceive: 4g");
                        mIReceiveMessage.onNetConnected();
                    }
                }
            } else {
                if (mIReceiveMessage != null) {
                    Log.e(TAG, "onReceive: 没网");
                    mIReceiveMessage.onNetDisConnected();
                }
            }
        }
    }
}
